<template>
	<a-modal
		:confirm-loading="loading"
		v-model:visible="visible"
		title="预设按钮"
		:width="600"
		:mask-closable="false"
		:destroy-on-close="true"
		@ok="onSubmit"
		@cancel="onClose"
	>
		<a-form>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="功能名称：">
						<a-input v-model:value="formData.name" placeholder="请输入功能名称" allow-clear @input="onInput" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="功能编码：">
						<a-input v-model:value="formData.code" placeholder="请输入功能编码" allow-clear @input="onInput" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<a-table
			:loading="loading"
			row-key="code"
			bordered
			size="small"
			:pagination="{ hideOnSinglePage: true }"
			:columns="columns"
			:data-source="dataSource"
			:row-selection="rowSelect"
		></a-table>
	</a-modal>
</template>

<script setup>
	import { cloneDeep, debounce } from 'lodash-es'
	import buttonApi from '@/api/sys/resource/buttonApi'

	const visible = ref(false)
	const loading = ref(false)
	const emit = defineEmits(['successful'])
	const baseCode = [
		{ title: '新增&Name&', code: '&Code&Add' },
		{ title: '编辑&Name&', code: '&Code&Edit' },
		{ title: '删除&Name&', code: '&Code&Delete' },
		{ title: '导出&Name&', code: '&Code&Export' },
		{ title: '导入&Name&', code: '&Code&Import' },
		{ title: '预览&Name&', code: '&Code&Preview' }
	]
	// 表格列
	const columns = [
		{ key: 'title', title: '名称', dataIndex: 'title' },
		{ key: 'code', title: '编码', dataIndex: 'code' },
		{ key: 'sortCode', title: '排序', dataIndex: 'sortCode' }
	]
	// 表格数据
	const dataSource = ref([])
	// 表单数据
	const formData = ref({
		name: '',
		code: ''
	})
	// 信息行数据
	let baseData = {}

	// 行选择
	const selectKeys = ref([])
	const rowSelect = computed(() => {
		return {
			selectedRowKeys: unref(selectKeys),
			onChange(keys) {
				selectKeys.value = keys
			}
		}
	})

	// 打开窗口
	const onOpen = (recordData) => {
		visible.value = true
		baseData = recordData
		// 触发输入事件，更新表格数据
		onInput()
	}

	// 输入事件
	const onInput = debounce(() => {
		dataSource.value = cloneDeep(baseCode).map((x) => {
			x.title = x.title.replace('&Name&', formData.value.name)
			x.code = x.code.replace('&Code&', formData.value.code)
			x.sortCode = 99
			return x
		})

		// 清空旧的选中
		selectKeys.value = []
	}, 200)

	// 提交信息
	const onSubmit = () => {
		loading.value = true
		buttonApi
			.buttonBatch({
				title: baseData.title,
				code: baseData.code,
				parentId: baseData.id,
				records: dataSource.value.filter((x) => selectKeys.value.includes(x.code)).map((x) => toRaw(x))
			})
			.then(() => {
				emit('successful')
				onClose()
			})
			.finally(() => {
				loading.value = false
			})
	}

	// 关闭窗口
	const onClose = () => {
		visible.value = false
	}

	defineExpose({ onOpen })
</script>

<style scoped></style>
